<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen">
        <template slot="handTimeSearch">
            <el-date-picker
              clearable
              v-model="dates2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </template>
        <template slot="searchMenu" slot-scope="{row,size}">
          <el-button :size="size" @click="()=>{searchFiledsEmpty(row);searchFiledsEmpty(searchForm)}" icon="el-icon-delete">清空</el-button>
        </template>
        <template slot-scope="scope" slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     v-permission="permissionList.informBtn"
                     @click.stop="handleBatchInfom()">通 知
          </el-button>
          <el-upload
            class="upload-inline"
            action=""
            :show-file-list="false"
            accept=".xls,.xlsx"
            :http-request="handleImportRecycle"
          >
            <el-button type="primary" size="small">导入</el-button>
          </el-upload>
          <el-button type="primary"
                     size="small"
		     :hidden="true"
                     v-if="false"
                     @click.stop="handleExport()">导 出
          </el-button>
          <el-button type="primary" size="small" @click.stop="handleInputDetail()">入 库</el-button>
          <el-button type="primary" size="small" @click.stop="handleOutputDetail()">出 库</el-button>
          <el-button type="primary" size="small" @click="rejectAudit">驳 回</el-button>
          <el-button type="primary" v-if="permissionList.superDelBatchs" size="small" @click="superDelBatchs">高级删除</el-button>
          <el-button type="primary"
                     size="small"
                     :hidden="true"
                     v-if="false"
                     v-permission="permissionList.exportBtn"
                     @click.stop="handlePrint()">打 印
          </el-button>
        </template>
        <template slot="menuRight">
          <el-button
            @click="handleDownloadClickRecovery"
            type="text"
            size="small"
          >模板下载</el-button>
        </template>
        <!-- <template slot="menuForm" slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click.stop="receivePerson2Confirm"
          >回收人2确认
          </el-button>
        </template> -->
        <template slot="swStTicketHandDetailsForm" slot-scope="scope">
          <dynamic-crud ref="dynamicCrud" :title="dynamicTitle" :data="detailList"
            :option="dynamicOption" :button="isLineNotice"
            :disabled="scope.disabled">
          </dynamic-crud>
        </template>
        <template slot="menu" slot-scope="{row, index}">
          <!-- <el-button type="text" size="small"
            v-if="row.dataSource=='0'&&row.noticeStatus=='0'"
            @click="rowEdit(row, index)">编 辑</el-button> -->
          <el-button type="text" size="small"
            v-if="row.handStatus=='0'"
            @click="showConfirm(row, index)">确 认</el-button>
          <el-button type="text" size="small"
                     v-if="row.handStatus=='1' && row.isOutstock == '0' && row.isInstock == '0'"
                     @click="recallShowConfirm(row)">撤回确认</el-button>
          <el-button type="text" size="small"
            v-if="row.handStatus=='3'"
            @click="appealFeedBack(row, index)">申诉反馈</el-button>
        </template>
      </avue-crud>
      <open-dialog titile="确 认" :DialogVisible.sync="dialogVisible">
        <avue-form v-model="form" :option="confirmOption">
          <template slot="swStTicketHandDetails" slot-scope="scope">
            <dynamic-crud :title="dynamicTitle" :data="detailList"
              :span-method="spanMethod"
              :option="dynamicOption" :button="false" :disabled="scope.disabled">
            </dynamic-crud>
          </template>
        </avue-form>
        <template slot="footer">
          <el-button type="primary" size="small" @click="confirmSubmit">确 认</el-button>
          <el-button size="small" @click="dialogVisible=false">取 消</el-button>
        </template>
      </open-dialog>
      <open-dialog titile="申诉反馈" :DialogVisible.sync="dialogVisibleAppeal">
        <avue-form v-model="form" :option="appealOption" v-if="dialogVisibleAppeal">
          <template slot="swStTicketHandDetails" slot-scope="scope">
            <dynamic-crud :title="dynamicTitle" :data="detailList"
              :span-method="spanMethod"
              :option="dynamicOptionAppeal" :button="false" :disabled="scope.disabled">
            </dynamic-crud>
          </template>
        </avue-form>
        <template slot="footer" v-if="dialogVisibleAppeal">
          <el-button type="primary" size="small" @click="appealSubmit">确 认</el-button>
          <el-button size="small" @click="dialogVisibleAppeal=false">取 消</el-button>
        </template>
      </open-dialog>
      <el-dialog
        title="驳回原因"
        :visible.sync="dialogVisibleRejectReply"
        width="30%"
      >
        <el-input type="textarea" v-model="param.rejectReply" maxlength="200" placeholder=""></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="setRejectReply()">确 认</el-button>
          <el-button  @click="dialogVisibleRejectReply=false">取 消</el-button>
        </span>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import baseCrud from '@/mixins/base-crud'
import {recallConfirm, batchDelete, inform, confirmOrFeedBack, getDetailObj, ImportRecycle, templateRecovery,inputDetailSubmitNew,outputDetailSubmit,exportExcel,rejectData} from '@/api/subway/swstticketrecycle'
import { startDate, endDate,startDate2,endDate2,appealOption } from "@/const/crud/subway/swstticketrecycle";
import {dateFormat} from '@/util/date'
import { handleExcelResponse } from "@/util/util";
import {checkPwd} from "@/api/admin/user";

export default {
  name: 'TicketRecycle',
  mixins: [baseCrud('subway/swstticketrecycle')],
  data() {
    return {
      boxType: '',
      previewDialogVisible: false,
      dialogVisible: false,
      dialogVisibleAppeal: false,
      dialogVisibleRejectReply: false,
      appealOption: appealOption,
      detailList: [],
      params: {
        //markId标识：1:车票上交 2:车票回收
        markId: 2,
        dates2: [startDate2, endDate2]
      },
      dates2: '',
      searchForm: {
        dates1: [startDate, endDate],
        handStatus: '0'
      },
      param: {
        rejectReply:'',//驳回原因
      }
    }
  },
  computed: {
    permissionList() {
      return {
        informBtn: this.vaildData(this.permissions.stm_sw_st_ticket_hand_inform, false),
        superDelBatchs: this.vaildData(this.permissions.stm_sw_st_ticket_hand_del, false),
      }
    },
    isLineNotice(){
      return this.form.dataSource == '0' || this.form.dataSource == '2' // 线路通知
    },
    dynamicTitle(){
      if(this.isLineNotice){
        return '回收明细信息'
      }else{
        return '上交明细信息'
      }
    },
    isAdd(){
      return this.boxType == 'add'
    },
    isConfirm(){
      return this.boxType == 'confirm'
    },
    isAppeal(){
      return this.boxType == 'appeal'
    },
    dynamicOption(){
      let isLine = this.isLineNotice
      return {
        column: [{
          label: '票种',
          prop: 'ticketType',
          type: 'select',
          cell: !this.isConfirm,
          dicUrl: '/support/swpmticketcardtype/dict',
          props: {
            label: 'mainName',
            value: 'mainEnName'
          },
          rules: [{
            required: true,
            message: '请选择票种'
          }],
          cascaderItem: ["ticketName"]
        }, {
          label: '车票名称',
          prop: 'ticketName',
          type: 'select',
          cell: this.isAdd,
          disabled: this.isAdd,
          dicUrl: '/support/swpmticketcardtypeparam/dictAll/{{key}}',
          props: {
            label: 'subName',
            value: 'subEnName'
          },
          component: 'ticket-name-select',
          params: {
            ticketAmountKey: 'ticketAmount',
            ticketCountKey: 'ticketCount'
          },
          width: 160,
          rules: [{
            required: true,
            message: '请选择车票名称'
          }]
        },
          {
            "label": "车票种类",
            "prop": "ticketReturnType",
            type: 'select',
            dicUrl: '/admin/dict/type/TICKET_RETURN_TYPE',
            // cell: this.isHandleResultEditable,
            cell: !this.isConfirm,
            disabled: this.isConfirm,
            // disabled: true,
            filterable: true,
            allowCreate: false,
            width: 110
          },
          {
          label: '号段',
          prop: 'numberInterval',
          cell: !this.isConfirm
        }, {
          type: "input",
          precision: 0,
          label: '有效期',
          prop: 'cardNumber',
          cell: !this.isConfirm
        }, {
          label: '金额',
          prop: 'ticketAmount',
          type: 'number',
          precision: 2,
        }, {
          label: '次数',
          prop: 'ticketCount'
        }, {
          label: '回收数量',
          prop: 'receiveCount',
          cell: !this.isConfirm,
          hide: !this.isAdd && !isLine,
          rules: [{
            required: true,
            message: '请输入回收数量'
          }]
        }, {
          label: '上交数量',
          prop: 'handCount',
          type: 'number',
          hide: this.isAdd
        }, {
          label: '实际回收张数',
          prop: 'realReceiveCount',
          type: 'number',
          hide: this.isAdd,
          cell: this.isConfirm
        }, {
          label: '差异张数',
          prop: 'differenceCount',
          type: 'number',
          hide: this.isAdd
        }, {
          label: '备注',
          prop: 'remark',
          cell: isLine
        }]
      }
    },
    dynamicOptionAppeal(){
      let isLine = this.isLineNotice
      return {
        column: [{
          label: '票种',
          prop: 'ticketType',
          type: 'select',
          dicUrl: '/support/swpmticketcardtype/dict',
          props: {
            label: 'mainName',
            value: 'mainEnName'
          },
          cascaderItem: ["ticketName"]
        }, {
          label: '车票名称',
          prop: 'ticketName',
          type: 'select',
          cell: !this.isConfirm,
          disabled: this.isConfirm,
          dicUrl: '/support/swpmticketcardtypeparam/dictAll/{{key}}',
          props: {
            label: 'subName',
            value: 'subEnName'
          },
          component: 'ticket-name-select',
          params: {
            ticketAmountKey: 'ticketAmount',
            ticketCountKey: 'ticketCount'
          },
          width: 160
        },
          {
            "label": "车票种类",
            "prop": "ticketReturnType",
            type: 'select',
            dicUrl: '/admin/dict/type/TICKET_RETURN_TYPE',
            // cell: !this.isConfirm,
            disabled: false,
            filterable: true,
            allowCreate: false,
            width: 110
          },
          {
          label: '号段',
          prop: 'numberInterval'
        }, {
          type: "input",
          precision: 0,
          label: '有效期',
          prop: 'cardNumber'
        }, {
          label: '金额',
          prop: 'ticketAmount',
          type: 'number',
          precision: 2,
        }, {
          label: '次数',
          prop: 'ticketCount'
        }, {
          label: '回收数量',
          prop: 'receiveCount',
          hide: !this.isAdd && !isLine,
          rules: [{
            required: true,
            message: '请输入回收数量'
          }]
        }, {
          label: '上交数量',
          prop: 'handCount',
          type: 'number',
          hide: this.isAdd
        }, {
          label: '实际回收张数',
          prop: 'realReceiveCount',
          type: 'number',
          hide: this.isAdd
        }, {
          label: '差异张数',
          prop: 'differenceCount',
          type: 'number',
          hide: this.isAdd
        }, {
          label: '备注',
          prop: 'remark'
        }]
      }
    },
    confirmOption(){
      let option = this.deepClone(this.tableOption)
      option.boxType = 'edit'
      option.menuBtn = false
      var rejectReply = this.findObject(option.group[2].column, "rejectReply");
      rejectReply.display = false
      option.group[0].display = true
      option.group[1].display = true
      option.group[3].display = true
      option.group[4].display = this.isLineNotice
      return option
    }
  },
  watch: {
    'dates2':{
      handler(newValue, oldValue){
        if(this.validatenull(newValue)){
          this.params.dates2[0] = '';
          this.params.dates2[1] = '';
        }else{
          this.params.dates2[0] = dateFormat(newValue[0]).substr(0, 10);
          this.params.dates2[1] = dateFormat(newValue[1]).substr(0, 10);
        }
      }
    }
  },
  methods: {
    async handleExport(){
      let loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      })
      try {
        let tableSelect = this.$refs.crud.tableSelect;
        let ids = tableSelect.map(row => row.id)
        let param = {
          ids: this.validatenull(ids)?null:ids
        };
        const res = await exportExcel(param);
        handleExcelResponse(res);
      } finally {
        loading.close();
      }
    },
    searchFiledsEmpty(form){
      //this.$delete(this.params,'dates2')
      this.dates2 = '';
      for (var i in form) {
        this.$delete(form,''+i+'')
      }
      this.getList(this.page);
    },
    handleInputDetail:function(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if(table.handStatus == "0"){
          this.$message.info("请选择已确认的数据!");
          return false;
        }
	if(table.isInstock=='1'){
	  this.$message.error("请检查选择的数据有已入库的数据，请重新选择！");
          return false;
	}
        ids.push(table.id);
      }
      this.$confirm("确认加入入库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        inputDetailSubmitNew(ids)
          .then(data => {
            this.$message.success("入库成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    handleOutputDetail:function(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if(table.isOutstock=='1'){
	  this.$message.error("请检查选择的数据有已出库的数据，请重新选择！");
          return false;
	}
        if(table.handStatus == "0"){
          this.$message.info("请选择已确认的数据!");
          return false;
        }
	if(table.isOutstock=='1'){
	  this.$message.error("请检查选择的数据有已出库的数据，请重新选择！");
          return false;
	}
        ids.push(table.id);
      }
      this.$confirm("确认加入出库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        outputDetailSubmit(ids)
          .then(data => {
            this.$message.success("出库成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {});
      });
    },
    receivePerson2Confirm() {
      if (!this.form.receivePersonTwoCode) {
        this.$message.info("请先选择回收人2");
        return;
      }
      this.$prompt("请输入密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (val) => {
          if (!val) return "请输入密码";
        },
      })
        .then(({value}) => {
          checkPwd(this.form.receivePersonTwoCode, value).then((response) => {
            var result = response.data.data;
            if (result) {
              this.$message.success("确认成功");
            } else {
              this.$message.error("密码错误");
            }
            //this.form.receivePerson2Confirmed = result;
          });
        })
        .catch(() => {
        });
    },
    async beforeRowSave(row, done, loading){
      if(this.detailList.length == 0){
        this.$message.info('请添加回收明细')
        loading()
        return
      }
      const formCellRules = this.$refs.dynamicCrud.$refs.crud.formCellRules;
      for(let index in this.detailList){
        if (this.detailList[index].ticketName == 'PTDCP'
          && (this.detailList[index].ticketReturnType == null || this.detailList[index].ticketReturnType == undefined || this.detailList[index].ticketReturnType == '')) {
          this.$message.info(`第${++index}行:普通单程票必须选择车票种类`)
          loading()
          return;
        }
        let result = await this.asyncValidator(formCellRules, this.detailList[index])
          .then(() => {return null})
          .catch(errors => {return errors})
        if(result){
          this.$message.info(`第${++index}行:${result[0].message}`)
          loading()
          return
        }
      }
      // if (!row.receivePerson2Confirmed) {
      //   this.$message.warning("请先进行回收人2确认");
      //   loading()
      //   return
      // }
      row.swStTicketHandDetails = this.detailList
      row.handStatus = '0'
      done()
    },
    beforeRowUpdate(row, index, done, loading){
      row.swStTicketHandDetails = this.detailList
      done()
    },
    handleBatchInfom(){
      var tableSelect = this.$refs.crud.tableSelect
      if(tableSelect.length == 0){
        this.$message.info('请选择要通知的记录')
        return
      }
      for (const table of this.$refs.crud.tableSelect) {
        if(table.noticeStatus == "1"){
          this.$message.info("请选择未通知的数据!");
          return false;
        }
      }
      var ids = tableSelect.map(row => row.id)
      this.$confirm("确认通知?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }).then(() => {
        inform(ids)
          .then(data => {
            this.$message.success("通知成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
      // inform(ids).then(response => {
      //   this.$message.success('通知成功')
      //   this.getList(this.page)
      // })
    },
    beforeOpen(done, type){
      this.boxType = type
      if(type == 'add'){
        for (var i in this.form) {
          this.form[i] = null;
        }
        setTimeout(()=>{
          this.form.dataSource = '0'
          this.detailList = []
          this.form.receiveTime = dateFormat(new Date());
          this.form.receivePersonName = this.$store.getters.userInfo.nikename;
          this.form.receivePersonCode = this.$store.getters.userInfo.userCode;
          this.form.receivePersonTwoName = this.$store.getters.userInfo.nikename;
          this.form.receivePersonTwoCode = this.$store.getters.userInfo.userCode;
        }, 0)
        done()
      }else{
        getDetailObj(this.form.id).then(response => {
          this.detailList = response.data.data.swStTicketHandDetails
          if(type == 'edit'){
            this.detailList.forEach(d => d.$cellEdit = true)
          }
          done()
        })
      }
    },
    preview(row){
      this.boxType = 'confirm';
      this.form = row;
      getDetailObj(this.form.id).then(response => {
        this.detailList = response.data.data.swStTicketHandDetails
        this.previewDialogVisible = true
      })
    },
    //撤回确认
    recallShowConfirm(row){
      console.log(JSON.stringify(row))
      recallConfirm(row.id).then(response => {
        this.$message.success('撤回确认成功')
        this.getList(this.page)
        done()
      }).catch(() => {
      })
    },
    showConfirm(row, index){
      this.boxType = 'confirm';
      this.form = row;
      getDetailObj(this.form.id).then(response => {
        this.detailList = response.data.data.swStTicketHandDetails
        this.detailList.forEach(d => {
          d.$cellEdit = true
          if (d.realReceiveCount == 0) {
            d.realReceiveCount = d.handCount
          }
        }
        )
        //如果是车站下发的就默认当前登录人
        if(this.form.dataSource == '1'){
          this.form.receiveTime = dateFormat(new Date());
          this.form.receivePersonName = this.$store.getters.userInfo.nikename;
          this.form.receivePersonCode = this.$store.getters.userInfo.userCode;
          this.form.receivePersonTwoName = this.$store.getters.userInfo.nikename;
          this.form.receivePersonTwoCode = this.$store.getters.userInfo.userCode;
        }
        this.dialogVisible = true
      })
    },
    appealFeedBack(row, index){
      this.boxType = 'confirm';
      this.form = row;
      getDetailObj(this.form.id).then(response => {
        this.detailList = response.data.data.swStTicketHandDetails
        this.dialogVisibleAppeal = true
      })
    },
    confirmSubmit(){
      for(const item of this.detailList){
        if(!this.validatenull(item.receiveCount) && item.receiveCount > 0){
          if(this.validatenull(item.realReceiveCount)||item.realReceiveCount<=0){
            this.$message.info("请填写实际回收张数！");
            return;
          }
        }
      }
      if (this.validatenull(this.form.receivePersonName) || this.validatenull(this.form.receivePersonCode) ||
          this.validatenull(this.form.receivePersonTwoName) || this.validatenull(this.form.receivePersonTwoCode) ||
          this.validatenull(this.form.receiveTime) ) {
          this.$message.warning("必填项不能为空！");
          return;
      }
      this.form.swStTicketHandDetails = this.detailList
      confirmOrFeedBack(this.form).then(response => {
        this.$message.success('确认成功')
        this.dialogVisible = false
        this.getList(this.page)
        done()
      }).catch(() => {
      })
    },
    appealSubmit(){
      this.form.swStTicketHandDetails = this.detailList
      confirmOrFeedBack(this.form).then(response => {
        this.$message.success('反馈成功')
        this.dialogVisibleAppeal = false
        this.getList(this.page)
        done()
      }).catch(() => {
      })
    },
    spanMethod({ row, column, rowIndex, columnIndex }){
      if(this.boxType == 'confirm'){
        if(!this.validatenull(row.realReceiveCount)){
          row.differenceCount = row.realReceiveCount - row.handCount
        }else{
          row.differenceCount = undefined
        }
      }
    },
    async handleDownloadClickRecovery () {//车票回收信息导出模板
      this.uploading = true;
      try {
        const res = await templateRecovery();
        handleExcelResponse(res);
      } finally {
        this.uploading = false;
      }
    },
    handleImportRecycle(item) {//车票回收信息导入
      this.$message.info("正在导入，请耐心等待！");
      let file = item.file;
      let param = new FormData();
      param.append("file", file);
      ImportRecycle(param).then(() => {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000
        });
        this.getList(this.page);
      });
    },
    //高级删除
    superDelBatchs(){
      var tableSelect = this.$refs.crud.tableSelect
      if(tableSelect.length == 0){
        this.$message.info('请选择要删除的记录')
        return
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const deletePromises = ids.map(id => batchDelete(id));
        Promise.all(deletePromises).then(response => {
          this.$message.success('删除成功')
          this.getList(this.page)
        })
      });
    },
    //驳回
    rejectAudit(){
      var tableSelect = this.$refs.crud.tableSelect
      var ids = tableSelect.map(row => row.id)

      if(tableSelect.length == 0){
        this.$message.warning('请选择要通知的记录')
        return false;
      }
      for (const table of this.$refs.crud.tableSelect) {
        if(table.dataSource != "1" && table.noticeStatus == "0"){
          this.$message.warning("请选择数据来源是车站并且是已通知的数据!");
          return false;
        }
      }
      this.dialogVisibleRejectReply=true;
      // let statusIds = [];
      // for(let i=0;i<this.selectKeys.length;i++){
      //   if(this.selectKeys[i].appealState==1 ){
      //     statusIds.push(this.selectKeys[i].appealState);
      //   }
      // }
      // if(statusIds.indexOf('1')>-1){//1代表未申诉
      //     this.$confirm("所选数据有车站人员还未确认，是否要审批？", "提示", {
      //       confirmButtonText: "确定",
      //       cancelButtonText: "取消",
      //       type: "warning",
      //     }).then(() => {
      //       this.dialogVisibleAppealReply=true;
      //     });
      // }else{
      //   this.dialogVisibleAppealReply=true;
      // }
    },
    setRejectReply(){//确认
      var tableSelect = this.$refs.crud.tableSelect;
      var ids = tableSelect.map(row => row.id);
      if(this.param.rejectReply==null || this.param.rejectReply=='' || this.param.rejectReply==undefined){
        this.$message.warning("请填写内容！");
        return false;
      }
      rejectData({rejectReply:this.param.rejectReply,ids:ids}).then(res=>{
        this.$message.success("驳回成功！");
        this.dialogVisibleRejectReply=false;
        this.getList(this.page);
        done()
      }).catch(() => {

      })
    },
  }
}
</script>

<style lang="scss" scoped>
</style>
